<template>
  <view class="free-payment">
    <common-popup :show="show" @close="close">
      <template #title>
        <view>会员充值</view>
      </template>
      <template>
        <view class="vip-recharge">
          <view class="member-info" v-if="selectMember">
            <view class="left flex">
              <view class="top flex">
                <view class="phone">
                  {{selectMember.member_name||'-'}}
                </view>
                <view class="phone">
                  {{selectMember.member_phone||'-'}}
                </view>
              </view>
              <view class="bottom flex justify-between">
                <view class="phone">
                  <text>￥{{selectMember.balance||'0'}}</text>
                  <text class="label">余额</text>
                </view>
                <view class="phone">
                  <text>{{selectMember.integral||'0'}}</text>
                  <text class="label">积分</text>
                </view>
              </view>
            </view>
          </view>
          <view class="form-box flex-1">
            <view class="form-item flex-column">
              <view class="check-list flex  align-center">
                <view class="check-item" v-for="item in rechargeList" @click="onSelect(item)"
                  :class="{active:current===item.setup_no}">
                  <!-- {{item.recharge_give}} -->
                  充{{item.recharge_amount}},送{{item.give_amount}}
                </view>
              </view>
              <view class="full input flex align-center ">
                <uni-easyinput type="digit" primaryColor='#38C09E' v-model="payAmount" placeholder="请输入自定义充值金额"
                  @focus="onSelect()">
                </uni-easyinput>
                <text class="margin-left text">
                  <text v-if="giftAmount&&!current">送{{giftAmount}}</text>
                </text>
              </view>
            </view>
            <view class="form-item flex-column">
              <view class="form-label">
                请选择支付方式
              </view>
              <view class="payment-grid">
                <view class="payment-item" :class="{disabled:item.disabled == true}"
                  @click="selectPayment(item.pay_type)" v-for="item in paymentList">
                  <image :src="item.image" mode="aspectFit"></image>
                  <text class="payment-item-label">{{item.label}}</text>
                </view>
              </view>
            </view>
          </view>
          <view class="form-bottom flex justify-between align-center">
            <view class=" flex-1">
              应付：<text class="text-red amount">￥{{needPay}}</text>
            </view>
          </view>
        </view>
      </template>
    </common-popup>


    <u-popup class="scan-code-popup" :show="showWindow" :round="20" mode="center" :overlay="true" :closeable="true"
      :closeOnClickOverlay="false" @close="isShowWindow()">
      <view style="padding:35px;">
        <view style="
    		width: 100%;
    		display: flex;
    		align-items: center;
    		justify-content: center;
    		height: 14rem;
    		font-size: 4rem;
    		font-weight: 600;
    		">
          请用扫描设备扫描支付二维码
        </view>
        <view style="margin-bottom: 32px;">
          <!--    <u-input :disabled="true" :customStyle="{height:`6.8rem !important`}" placeholder="请扫支付码" border="surround"
            v-model="codeInputValue" ref="codeInput"></u-input> -->
          <u-loading-icon text="支付中" textSize="18" v-if="isPaying===true"></u-loading-icon>
          <view class="text-red text-center" v-else-if="isPaying==='支付超时'">
            支付超时！
          </view>
        </view>
      </view>
    </u-popup>

    <u-modal class="custom-u-modal" width="30vw" confirmColor="#38C09E" :show="showModal" :title="modalTitle"
      :content='modalContent' :showCancelButton="true" @confirm="confirmRecharge" @cancel="hideModal"></u-modal>
  </view>
</template>

<script>
  import {
    watchKeydown
  } from '@/common/utils/input.js'


  /**
   * @description 会员充值弹窗
   * @property {Boolean} show - 是否显示充值弹窗
   * @property {String} memberNo - 当前选择会员的会员编号
   * @property {String} curSelectMember - 当前选择的会员信息 跟会员编号（memberNo）只需要传任意一个就行
   * @event {Function()} close - 弹窗关闭事件，点击右上角关闭图标或者右下角取消按钮时触发
   * @event {Function()} success - 充值成功事件
   * @event {Function()} fail - 充值失败事件
   * @example   <vip-recharge :show="show" @close="close" @success=""></vip-recharge>
   */
  export default {
    name: "vip-recharge",
    props: {
      // 显示会员充值弹窗
      show: {
        type: Boolean,
        default: false
      },
      // 当前选择会员的会员编号
      memberNo: {
        type: String
      },
      // 当前选择的会员
      curSelectMember: {
        type: Object,
      },
      // codeInputValue: String,
      // showWindow: Boolean
    },

    computed: {
      currentSetup() {
        return this.rechargeList.find(item => item.setup_no === this.current)
      },
      rechargeList() {
        return this.giftAmountList.filter(item => item.member_level_no === this.curSelectMember?.member_level_no)
      },
      memberSetup() {
        return this.$store.state?.$memberSetup
      },
      selectMember() {
        if (this.memberNo) {
          return this.memberList.find(item => item.mem)
        } else {
          return this.curSelectMember
        }
      },
      totalAmount() {
        return Number(this.giftAmount + this.needPay)
      },
      giftAmount() {
        if (!this.payAmount && this.current) {
          return this.currentSetup?.give_amount
        } else {
          let current = this.rechargeList.find(item => item.recharge_amount === this.needPay)
          if (current?.give_amount) {
            return current?.give_amount
          } else {
            let rechargeList = this.rechargeList.filter(item => item.recharge_amount <= this.needPay)
            rechargeList = rechargeList.sort((a, b) => b.recharge_amount - a.recharge_amount)
            if (rechargeList.length > 0) {
              return rechargeList[0]?.give_amount
            }
          }
          return 0
        }
      },
      needPay() {
        if (!this.payAmount && this.current) {
          return this.currentSetup?.recharge_amount
        }
        return !isNaN(Number(this.payAmount)) ? Number(this.payAmount) : ''
      }
    },
    data() {
      return {
        random: '',
        showModal: false,
        modalTitle: "",
        modalContent: "",
        payAmount: "",
        current: "",
        curPayment: "现金",
        radio2List: [{
            name: "现金",
            image: "/static/icons/xj.png"
          },
          // {
          //   name: "扫一扫",
          //   image: "/static/icons/sys.png"
          // }
        ],
        giftAmountList: [],
        paymentList: [],
        onCashPay: false, //现金支付
        isPaying: false,
        codeInputValue: '',
        showWindow: false
      };
    },
    mounted() {
      this.registerKeydow()
    },
    beforeDestroy() {
      this.removeKeydown()
    },
    methods: {
      async onWatchKeydown(e) {
        watchKeydown(e, '11111').then(str => {
          if (this.showWindow) {
            this.codeInputValue = str;
            if (this.codeInputValue) {
              let valid = false
              let code = this.codeInputValue + ''
              if (this.curPayment == '微信') {
                if (/^1[0-5]\d{16}$/.test(code)) {
                  valid = true
                }
              } else if (this.curPayment == '支付宝') {
                if (/^(?:2[5-9]|30)\d{14,22}$/.test(code)) {
                  valid = true
                }
              } else if (this.curPayment == '银联') {
                if (/^62\d{0,32}$/.test(code)) {
                  valid = true
                }
              }
              if (valid === false) {
                this.$emit("update:showWindow", false)
                uni.showToast({
                  title: '非' + this.curPayment + '付款码',
                  icon: 'none'
                })
                return
              }
            } else {
              return
            }

            uni.showLoading({
              title: '支付中'
            })
            this.mobilePay()
            setTimeout(() => {
              uni.hideLoading()
            }, 3000)
          } else {}
        })
      },
      removeKeydown() {
        // 移除键盘按下监听事件
        // #ifdef APP-PLUS
        plus.key.removeEventListener('keydown', this.onWatchKeydown)
        // #endif
        // #ifdef H5
        window.document.removeEventListener('keydown', this.onWatchKeydown)
        // #endif
      },
      registerKeydow() {
        // 注册键盘按下监听事件 监听码枪输入
        // #ifdef APP-PLUS
        plus.key.addEventListener('keydown', this.onWatchKeydown)
        // #endif
        // #ifdef H5
        window.document.onkeydown = this.onWatchKeydown
        // #endif
      },
      isShowWindow(e = false) {
        this.isPaying = false
        this.showWindow = false
        // this.$emit('showWindow', e)
      },
      mobilePay() {
        const keyMap = {
          '微信': 'wx_pay',
          '支付宝': 'ali_pay',
          '银联支付': 'union'
        }
        const req = [{
          "serviceName": "srvls_m_charge_b_scan_c_pay",
          "data": [{
            "member_phone": this.curSelectMember?.member_phone,
            "member_no": this.curSelectMember?.menber_no,
            "authCode": this.codeInputValue,
            "remark": "",
            "pay_way": keyMap[this.curPayment],
            "channel_source": "台式消费机",
            "gift_amount": this.giftAmount,
            // "recharge_amount": 0.01
            "recharge_amount": this.needPay
          }]
        }]

        const url = `/retail/operate/srvls_m_charge_b_scan_c_pay`
        this.$http.post(url, req).then(res => {
          uni.hideLoading()
          let timer = null
          if (res?.data?.resultCode === 'SUCCESS') {
            this.$emit('rechargeSuccess', res?.data?.resultCode)
            this.$emit('success', '操作成功')
          } else if (res?.data?.resultCode === 'USERPAYING') {
            this.isPaying = true
            const record_no = res?.data?.response?. [0]?.response?.record_no
            const interval = setInterval(() => {
              this.selectPayState(record_no).then((state) => {
                if (state === true) {
                  clearTimeout(timer)
                  clearInterval(interval)
                  this.isPaying = false
                  this.$emit('rechargeSuccess', 'SUCCESS')
                  this.$emit('success', '操作成功')
                }
              })
            }, 1000)
            timer = setTimeout(() => {
              this.isPaying = '支付超时'
              clearInterval(interval)
            }, 20 * 1000)
          } else {
            uni.showToast({
              title: res?.data?.resultMessage,
              icon: "none"
            })
          }
        }).catch(() => {
          this.$emit('rechargeSuccess', 'SUCCESS')
          this.$emit('fail', '操作失败')
        })
      },
      async selectPayState(record_no) {
        const url = `/retail/select/srvretail_member_recharge_flow_select`
        const req = {
          serviceName: "srvretail_member_recharge_flow_select",
          colNames: ['*'],
          condition: [{
            colName: 'record_no',
            ruleType: 'eq',
            value: record_no
          }]
        }
        const res = await this.$http.post(url, req)
        if (res?.data?.state === 'SUCCESS' && res.data.data.length > 0) {
          let data = res.data.data[0]
          if (data?.pay_state == 'SUCCESS') {
            return true
          } else {
            return false
          }
        }
        return false
      },
      selectPayment(e) {
        if (!this.needPay) {
          uni.showToast({
            title: '请选择或输入充值金额',
            icon: 'none'
          })
          return
        }
        this.curPayment = e;
        if (e == '现金') {
          this.confirm()
        } else if (e == "微信" || e == '支付宝' || e == "银联支付") {
          // this.$emit("showWindow", true)
          this.showWindow = true
        }
      },
      // 查找支付方式
      getPayWayList() {
        const service = 'srvretail_pay_set_select'
        const url = `/retail/select/${service}`;
        const req = {
          "serviceName": service,
          "colNames": ["*"],
        };
        uni.showLoading({
          title: "加载中"
        })
        this.$http.post(url, req).then(res => {
          if (res?.data?.state === 'SUCCESS') {
            this.paymentList = res?.data?.data.filter(item => item.pay_type !== '会员卡').map(
              item => {
                let timeUnique = `${Math.random()*1000}${new Date().getTime()}`;
                item.unique = timeUnique;
                if (item.pay_status == '启用') {
                  item.disabled = false;
                } else {
                  item.disabled = true;
                }
                if (item.pay_type == '会员卡') {
                  item.label = '会员支付';
                  item.image = '/static/icons/hyzf.png';
                } else if (item.pay_type == '现金') {
                  item.label = '现金支付';
                  item.image = '/static/icons/xjzf.png';
                } else if (item.pay_type == '支付宝') {
                  item.label = '支付宝支付';
                  item.image = '/static/icons/zfb.png';
                } else if (item.pay_type == '微信') {
                  item.label = '微信支付';
                  item.image = '/static/icons/wxzf.png';
                } else if (item.pay_type == '积分') {
                  item.label = '积分支付';
                  item.image = '/static/icons/wxzf.png';
                } else if (item.pay_type == '银联支付') {
                  item.label = '银联支付';
                  item.image = '/static/icons/hbzf.png';
                } else if (item.pay_type == '和包') {
                  item.label = '和包支付';
                  item.image = '/static/icons/hbzf.png';
                } else if (item.pay_type == '数字人民币') {
                  item.label = '数字人民币支付';
                  item.image = '/static/icons/hbzf.png';
                }
                return {
                  ...item
                }
              })
          }
          uni.hideLoading()
        }).catch(_ => {
          uni.hideLoading()
        })
      },
      // 查找会员充值增额信息
      async getGiftAmountList() {
        const service = `srvretail_recharge_give_amount_select`
        const url = `/retail/select/${service}`
        const req = {
          "serviceName": "srvretail_recharge_give_amount_select",
          "colNames": ["*"],
          "condition": [{
            "colName": "member_setup_no",
            "ruleType": "eq",
            "value": this.memberSetup?.member_setup_no
          }],
        }
        const res = await this.$http.post(url, req)
        if (res.data.state == 'SUCCESS') {
          this.giftAmountList = res.data.data
          let list = this.giftAmountList.filter(item => item.member_level_no === this.curSelectMember
            ?.member_level_no)
          if (Array.isArray(list) && list.length > 0) {
            this.current = list[0].setup_no
          }
        }
      },

      hideModal() {
        this.showModal = false
      },
      confirm() {
        if (this.curPayment === '现金') {
          this.modalTitle = '现金支付/线下支付'
          this.modalContent = '请确认是否已完成支付!如点击确认,该订单将无法更换其他支付方式支付。'
          this.showModal = true
        }
      },
      confirmRecharge() {
        const url = `/retail/operate/srvretail_recharge_adjustment_consumption_add`
        const req = [{
          "serviceName": "srvretail_recharge_adjustment_consumption_add",
          "condition": [],
          "data": [{
            "member_no": this.selectMember?.menber_no,
            "member_name": this.selectMember?.member_name,
            "member_phone": this.selectMember?.member_phone,
            // "usable_recharge_amount": 0,
            // "usable_gift_amount": 0,
            "operation_type": "充值",
            "recharge_amount": this.needPay,
            "gift_amount": this.giftAmount,
            "total_amount": this.totalAmount,
            "payment_method": this.curPayment,
            // "remark": "充值",
            "channel_source": "台式消费机", //渠道来源
            "record_type": "会员充值", //记录类型
            // "record_type": "手动调整"
          }]
        }]
        this.hideModal()
        if (this.curPayment === '现金') {
          this.$http.post(url, req).then(res => {
            if (res?.data?.state === 'SUCCESS') {
              this.$emit('rechargeSuccess', 'SUCCESS')
              this.$emit('success', res.data.resultMessage)
              // uni.showModal({
              //   title:'提示',
              //   content:'充值成功',
              //   success: (r) => {
              //     if(r.confirm){
              //       this.$emit('success', res.data.resultMessage)
              //     }
              //   }
              // })

            } else {
              this.$emit('fail', res.data.resultMessage)
              uni.showToast({
                title: res.data.resultMessage,
                icon: 'none'
              })
            }
          })
        }
      },

      onSelectPayment(e) {
        this.curPayment = e
      },
      onSelect(e) {
        this.current = e?.setup_no
        if (e) {
          this.payAmount = ''
        }
      },
      close() {
        this.$emit('close')
      }
    },
    created() {
      if (this.memberSetup?.member_setup_no) {
        this.getGiftAmountList()
      }
      this.getPayWayList()
    }
  }
</script>

<style lang="scss" scoped>
  .vip-recharge {
    min-width: 40vw;
    max-width: 60vw;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .text-area {
    width: 100%;
    border-radius: 1rem;
    background-color: #f5f5f5;
    padding: 2rem;
    min-height: 10rem;
  }

  ::v-deep .input {

    uni-input,
    .uni-input,
    .uni-input-placeholder {
      font-size: 2.4rem;
    }
  }

  .member-info {
    display: flex;
    width: 100%;
    height: 15rem;
    background-color: $retail-color-primary;
    border-radius: 1rem;
    // margin-bottom: 2rem;
    margin-top: 2rem;
    color: #fff;

    .left {
      padding: 1.6rem 2rem;
      flex: 1;
      display: flex;
      // flex-direction: column;
      // margin-right: 5rem;
      justify-content: space-between;
      align-items: center;

      .top {
        flex: 1;
        font-weight: 700;
        display: flex;
        justify-content: flex-start;
        font-size: 2.8rem;

        .phone {
          margin-right: 2rem;
        }
      }

      .bottom {
        font-size: 2rem;
        display: flex;
        flex: 1;

        .phone {
          display: flex;
          flex: 1;
          flex-direction: column;
          text-align: right;
          font-size: 2.8rem;

          .label {
            font-size: 2rem;
            margin-top: 1rem;
          }
        }
      }
    }

    .right {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: 1rem;

      .button {
        width: 7rem;
        height: 4rem;

        &.bg-white {
          background-color: #fff;
          color: #333;
        }
      }
    }
  }

  .form-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-top: 1.5rem;

    &.flex-column {
      flex-direction: column;
      align-items: flex-start;

      .form-label {
        padding-top: 0;
      }
    }

    &.label-top {
      align-items: flex-start;

      .form-label {
        // padding-top: 0;
      }
    }

    .input {
      margin-top: 2rem;
      // width: 50%;
      width: 100%;

      .text {
        width: 50%;
      }

      .uni-easyinput {
        flex: 1;
      }
    }

    .form-label {
      font-size: $retail-font-size-sm;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      text-align: left;
      padding: 1.5rem 0;
      margin-right: 1rem;
      min-width: 10rem;

    }

    .form-input {
      border: 1px solid #e5e5e5;
      border-radius: 1rem;
      height: 6rem;
      padding: 1.5rem;
      width: 32rem;
    }

    .form-radio {
      width: 32rem;
      display: flex;
      align-items: center;
    }

    .form-textarea {
      width: 32rem;
      height: 10rem;
      background-color: #f5f5f5;
      padding: 1.5rem;
      border-radius: 1rem;
    }
  }


  .check-list {
    display: flex;
    width: 100%;
    flex-wrap: wrap;

    &.w-half {
      width: 50%;
    }

    &.justify-start {
      justify-content: flex-start;
    }
  }

  .check-item {
    // padding: 1.3rem 2rem;
    padding: .5rem;
    // margin-bottom: 1rem;
    margin-right: 2rem;
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 13.5rem;
    height: 6rem;
    text-align: center;
    border-radius: 1rem;
    border: 1px solid #e5e5e5;
    color: #333;
    font-size: $retail-font-size-sm;
    width: 17rem;
    display: flex;
    justify-content: center;
    font-size: 2.4rem;
    // flex: 1;
    margin-bottom: 1rem;

    .image {
      width: 3.5rem;
      height: 3.5rem;
      margin-right: 3rem;
    }

    &.active {
      border-color: $retail-color-primary;
      // color: $retail-color-primary;
      background-color: $retail-color-primary-light;
    }
  }

  .form-bottom {
    font-size: 2.4rem;

    .amount {
      font-size: 3.6rem;
      font-weight: 700;
    }
  }

  .payment-grid {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    max-width: 600px;
    margin-bottom: 2rem;

    .payment-item {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 25%;
      // padding: 1rem;
      font-size: $retail-font-size-sm;

      &.disabled {
        filter: grayscale(100%);
      }

      &.active {
        background-color: $retail-color-primary;
        color: #fff;
        border-radius: 1rem;
      }

      image {
        border-radius: 1rem;
        width: 9.6rem;
        height: 9.6rem;
      }

      .payment-item-label {
        padding: 1rem;
        font-size: 2rem;
      }
    }
  }

  ::v-deep .scan-code-popup {
    .u-transition.u-fade-zoom-enter-to.u-fade-zoom-enter-active {
      z-index: 9999999999 !important;
    }

    .u-transition.u-fade-enter-to.u-fade-enter-active {
      z-index: 999999999 !important;
    }
  }
</style>
